package com.database.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rent.common.api.ApiString;
import com.rent.common.constants.ConstantsBase;
import com.rent.common.pojo.ResultJSON;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.List;

/**
 * @Author zhang
 * @create 2022/9/12 11:15
 */
public interface QueryController<T, PK extends Serializable> extends BaseController<T, PK> {


    default ResultJSON<PageInfo<T>> pageList(@PathVariable(required = false) Integer page,
                                             @PathVariable(required = false) Integer size,
                                             @RequestBody(required = false) T model) {
        if (page == null) page = 1;
        if (size == null) size = ConstantsBase.PAGE_SIZE;
        //分页
        PageHelper.startPage(page, size);
        List<T> list = getSuperService().selectListBySearch(model);
        if (CollectionUtils.isEmpty(list)) return ResultJSON.failure(ApiString.selectFail);
        PageInfo<T> pageInfo = new PageInfo<>(list);
        return ResultJSON.success(ApiString.selectSuccess, pageInfo);
    }

    default ResultJSON<List<T>> findList(@RequestBody(required = false) T model) {
        List<T> list = getSuperService().selectListBySearch(model);
        if (CollectionUtils.isEmpty(list)) return ResultJSON.failure(ApiString.selectFail);
        return ResultJSON.success(ApiString.selectSuccess, list);
    }

    default ResultJSON<T> getByKey(@PathVariable PK key) {
        T model = getSuperService().selectByPrimaryKey(key);
        if (model == null) return ResultJSON.failure(ApiString.selectFail);
        return ResultJSON.success(ApiString.selectSuccess, model);
    }


}
